package com.aishua.aishuawallet.business;

import android.content.Context;
import android.util.Log;

import com.aishua.aishuawallet.Constant;
import com.aishua.aishuawallet.bean.Header;
import com.aishua.aishuawallet.bean.ReqAuthBean;
import com.aishua.aishuawallet.bean.ReqTokenCreateBean;
import com.aishua.aishuawallet.bean.ReqTransBean;
import com.aishua.aishuawallet.engin.IResponseListener;
import com.aishua.aishuawallet.engin.SocketManager;
import com.aishua.aishuawallet.longconnection.ClientSocket;
import com.aishua.aishuawallet.mina.MianManager;
import com.aishua.aishuawallet.mina.MinaResultLIstener;
import com.aishua.aishuawallet.utils.AndroidUtils;
import com.aishua.aishuawallet.utils.CacheUtils;
import com.aishua.aishuawallet.utils.LogUtils;
import com.aishua.aishuawallet.utils.SHA256Util;

import org.web3j.crypto.Credentials;
import org.web3j.crypto.RawTransaction;
import org.web3j.crypto.TransactionEncoder;
import org.web3j.utils.Convert;
import org.web3j.utils.Numeric;

import java.math.BigInteger;


/**
 * Created by aishua on 2018/8/8.
 */

public class TaskBusiness implements BussinessInterface {

    private static final String TAG = "TaskBusiness--";
    private volatile static TaskBusiness taskbusiness;
    private MianManager mm;

    private TaskBusiness() {

        mm = MianManager.getManager();

    }

    public static TaskBusiness getInstance() {

        if (taskbusiness == null) {
            synchronized (TaskBusiness.class) {

                if (taskbusiness == null) {
                    taskbusiness = new TaskBusiness();
                }
            }
        }
        return taskbusiness;
    }


    @Override
    public void doAuth(Context mcontext, String authtype, String commandid, String phone, String pw, MinaResultLIstener minaResultLIstener) {

        final String message = getAuthInfoTCP(mcontext, authtype, commandid, phone, pw);
        LogUtils.v(TAG + "message:" + message);
        mm.request(mcontext, message, minaResultLIstener);


    }

    @Override
    public void TokenCreate(Context mContext, String tokenname, MinaResultLIstener minaResultLIstener) {

        final String message = getCreateinfoTCP(mContext, tokenname);
        LogUtils.v(TAG + "message:" + message);
        mm.request(mContext, message, minaResultLIstener);

    }

    @Override
    public void NotifyCreatSuc(Context mContext, MinaResultLIstener minaResultLIstener) {

        String notify = getHeartTCP("5011");
        LogUtils.v(TAG + "notify:" + notify);
        mm.request(mContext, notify, minaResultLIstener);

    }

    @Override
    public void Transaction(Context mContext, String tokenid, String tokenaddr, String ethcount, String gasprice, String gaslimit, String nonce, String hexdata, MinaResultLIstener minaResultLIstener) {

        String transaction = getTransactionTCP(mContext, tokenid, tokenaddr, ethcount, gasprice, gaslimit, nonce, hexdata);
        LogUtils.v(TAG + "transaction:" + transaction);
        mm.request(mContext, transaction, minaResultLIstener);
    }

    private String getTransactionTCP(Context mContext, String tokenid, String tokenaddr, String ethcount, String gasprice, String gaslimit, String nonce, String hexdata) {

        LogUtils.v(TAG+"tokenaddr:"+tokenaddr+"ethcount:"+ethcount+"gasprice:"+gasprice+"gasplimit:"+gaslimit+"nonce:"+nonce);

        BigInteger nonce1 = new BigInteger(nonce);
        BigInteger gasprice1 = new BigInteger(gasprice);
        BigInteger gaslimit1 = new BigInteger(gaslimit);
        BigInteger ethcount1 = new BigInteger(ethcount);

        RawTransaction rawTransaction1 = RawTransaction.createEtherTransaction(
                nonce1, gasprice1, gaslimit1, tokenaddr, ethcount1);


        Credentials credentials = Credentials.create("54f8c56ab1ed5e075326badf64eb60b4c174fe34c3d7fa51cf2bf64266a85123");

        //签名Transaction，这里要对交易做签名
        byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction1, credentials);
        String hexValue = Numeric.toHexString(signedMessage);
        LogUtils.v(TAG+"HEXVALUE:"+hexValue);


        ReqTransBean reqTransBean = new ReqTransBean();
        String time = AndroidUtils.getCurrentTime();
        reqTransBean.setTimestamp(time);
        reqTransBean.setClientver("01010001");
        reqTransBean.setOpttype("05");
        String phone = CacheUtils.getLoginname(mContext, Constant.PHONE);
        reqTransBean.setUsermobile(phone);
        reqTransBean.setTokenid(tokenid);

        ReqTransBean.RawTransaction rawTransaction = reqTransBean.new RawTransaction();

        String tokenaddrlen = String.format("%02X", tokenaddr.length());
        tokenaddr = tokenaddrlen + tokenaddr;
        rawTransaction.setAddress(tokenaddr);

        String ethcountlen = String.format("%02X", ethcount.length());
        ethcount = ethcountlen + ethcount;
        rawTransaction.setEthcount(ethcount);

        String gaspricelen = String.format("%02X", gasprice.length());
        gasprice = gaspricelen + gasprice;
        rawTransaction.setGasprice(gasprice);

        String gaslimitlen = String.format("%02X", gaslimit.length());
        gaslimit = gaslimitlen + gaslimit;
        rawTransaction.setGaslimit(gaslimit);

        String noncelen = String.format("%02X", nonce.length());
        nonce = noncelen + nonce;
        rawTransaction.setNonce(nonce);

        String hexdatalen = String.format("%02X", hexdata.length());
        hexdata = hexdatalen + hexdata;
        rawTransaction.setHexdata(hexdata);

        reqTransBean.setRawTransaction(rawTransaction);

        reqTransBean.setCommand_ID("4050");
        reqTransBean.setVersion("0311");
        reqTransBean.setOrderID("0000");
        reqTransBean.setSenderCode("00000000000000000000");

        String data = reqTransBean.requestString();


        return data;
    }

    private String getHeartTCP(String commid) {

        Header header = new Header();
        header.setVersion("0311");
        header.setOrderID("0000");
        header.setCommand_ID(commid);
        header.setSenderCode("00000000000000000000");
        String data = header.requestString();
        return data;
    }

    private String getCreateinfoTCP(Context mContext, String tokenname) {

        LogUtils.v(TAG + "tokenname:" + tokenname);
        ReqTokenCreateBean reqTokenCreateBean = new ReqTokenCreateBean();
        String time = AndroidUtils.getCurrentTime();
        reqTokenCreateBean.setTimestamp(time);
        reqTokenCreateBean.setClientVer("01010001");
        reqTokenCreateBean.setOptType("01");
        String phone = CacheUtils.getLoginname(mContext, Constant.PHONE);
        reqTokenCreateBean.setUserMobile(phone);
//        reqTokenCreateBean.setUserMobile("15210012925");
        tokenname = AndroidUtils.stringToUnicode(tokenname);
        LogUtils.v(TAG + "tokenname:" + tokenname);
        String name = AndroidUtils.unicode2String(tokenname);
        LogUtils.v(TAG + "NAME:" + name);
        LogUtils.v(TAG + "tokennameunicode:" + tokenname);
        String hexlength = String.format("%02X", tokenname.length());
        tokenname = hexlength + tokenname;
        reqTokenCreateBean.setTokenName(tokenname);

        reqTokenCreateBean.setVersion("0311");
        reqTokenCreateBean.setOrderID("0000");
        reqTokenCreateBean.setCommand_ID("4010");
        reqTokenCreateBean.setSenderCode("00000000000000000000");

        LogUtils.v("phone：" + phone);
        String data = reqTokenCreateBean.requestString();
        return data;
    }

    private String getAuthInfoTCP(Context mContex, String authtype, String commandid, String phone, String pw) {

        ReqAuthBean registbean = new ReqAuthBean();
        String time = AndroidUtils.getCurrentTime();
        registbean.setTimestamp(time);
        registbean.setClientVer("01010001");
        registbean.setAuthType(authtype);
        if (authtype.equals("03")){

            registbean.setUserMobile("00000000000");
            registbean.setUserPW("");

        }else {

            registbean.setUserMobile(phone);
            String sha256pw = SHA256Util.getSHA256StrJava(pw);
            sha256pw = sha256pw.substring(0, 16);
            registbean.setUserPW(sha256pw);
            LogUtils.v("sha256pw：" + sha256pw);

        }

        String iccid = AndroidUtils.getICCID(mContex);
        registbean.setICCID(iccid);
        String imei = AndroidUtils.getIMEI(mContex);
        registbean.setIMEI(imei);

        registbean.setCommand_ID(commandid);
        registbean.setVersion("0311");
        registbean.setOrderID("0000");
        registbean.setSenderCode("00000000000000000000");

        LogUtils.v("phone：" + phone);
        LogUtils.v("iccid:" + iccid);
        LogUtils.v("imei:" + imei);

        String data = registbean.requestString();


        return data;

    }

}
